/**
 * Copyright (c) 2013-1-6 上午11:44:36 WKM and/or its affiliates. 
 * Use is subject to license terms.
 * All rights reserved.
 */
package org.wkm.frame;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;

import net.sourceforge.jdatepicker.DateModel;
import net.sourceforge.jdatepicker.JDateComponentFactory;
import net.sourceforge.jdatepicker.impl.JDatePanelImpl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wkm.frame.listener.DefaultWindowListener;
import org.wkm.task.Tasks;
import org.wkm.task.file.DataReader;

import com.birosoft.liquid.LiquidLookAndFeel;

/**
 * @author WKM
 * JDatePickerFrame.java history
 * 1.WKM - 2013-1-6 - Create File
 */
public class JDatePickerFrame extends JFrame{

	/** 配置文件 **/
	private static DataReader READER = DataReader.getInstance();
	
	/** 设置时间窗口 **/
	private static JDatePickerFrame FRAME = null;
	
	/** 日志信息 **/
	private static Logger logger = LoggerFactory.getLogger(JDatePickerFrame.class);
	
	/** 当前选择时间 **/
	public static Calendar currentTime = null;
	
	/** 小时 **/
	public static JComboBox<Integer> hour = null;
	
	/** 分 **/
	public static JComboBox<Integer> minute = null;
	
	/** 任务调用 **/
	private static Tasks task = null;
	
	/**
	 * 唯一标识
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * 私有的构造单例
	 */
	private JDatePickerFrame(){
		logger.info("构造日历时间窗口...");
	}

	/**
	 * 窗口初始化
	 */
	private void initialize(){
		DateModel<?> model = JDateComponentFactory.createDateModel(Calendar.class);
		model.setYear(currentTime.get(Calendar.YEAR));
		model.setMonth(currentTime.get(Calendar.MONTH));
		model.setDay(currentTime.get(Calendar.DAY_OF_MONTH));
		JDatePanelImpl panel = new JDatePanelImpl(model);
		JPanel northPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
		JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
		JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
		
		hour = new JComboBox<Integer>();
		hour.setPreferredSize(new Dimension(60,20));
		currentTime.add(Calendar.MINUTE, 10);
		for(int i=0;i < 24;i++){
			hour.addItem(i);
		}
		for(int i=0;i < hour.getItemCount();i++){
			if(hour.getItemAt(i) == currentTime.get(Calendar.HOUR_OF_DAY)){
				hour.setSelectedIndex(i);
			}
		}
		hour.setEditable(true);
		
//		hour.setText(currentTime.get(Calendar.HOUR_OF_DAY) + "");
		
//		hour.setEditable(true);
//		hour.getDocument().addDocumentListener(new TextFieldValueChanage());
		
		minute = new JComboBox<Integer>();
		minute.setPreferredSize(new Dimension(60,20));
		for(int i=0;i < 60;i++){
			minute.addItem(i);
		}
		for(int i=0;i < minute.getItemCount();i++){
			if(minute.getItemAt(i) == currentTime.get(Calendar.MINUTE)){
				minute.setSelectedIndex(i);
			}
		}
		minute.setEditable(true);
		
//		minute.setText(currentTime.get(Calendar.MINUTE) + "");
//		minute.getDocument().addDocumentListener(new TextFieldValueChanage());
		JTextField second = new JTextField();
		second.setPreferredSize(new Dimension(20,20));
		second.setEditable(true);
		
		JLabel timeLabel = new JLabel("时间:");
		timeLabel.setPreferredSize(new Dimension(40,20));
		timeLabel.setFont(new Font("黑体",Font.BOLD,12));
		JLabel first = new JLabel(":");
//		JLabel seconds = new JLabel(":");
		JPanel timePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
		timePanel.setPreferredSize(new Dimension(300,20));
		timePanel.add(timeLabel);
		timePanel.add(hour);
		timePanel.add(first);
		timePanel.add(minute);
//		timePanel.
		JButton sure = new JButton(READER.getProperty("system.button.ok"));
		JButton cancel = new JButton(READER.getProperty("system.button.cancel"));
		sure.addActionListener(new ActionListener(){

			/**
			 * (non-Javadoc)
			 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
			 */
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(currentTime == null){
					MessageBox.showMessageBox(READER.getProperty("message.frame.title"), "时间设定不正确,系统出现故障,请重启系统!");
					return;
				}
				int hou = Integer.parseInt(hour.getSelectedItem().toString());
				int min = Integer.parseInt(minute.getSelectedItem().toString());
				currentTime.set(Calendar.HOUR_OF_DAY, hou);
				currentTime.set(Calendar.MINUTE, min);
				if(currentTime.getTimeInMillis() <= Calendar.getInstance().getTimeInMillis()){
					MessageBox.showMessageBox(READER.getProperty("message.frame.title"), "输入时间不能比现在时间早!");
					return ;
				}
				logger.info("输入时间为:" + new SimpleDateFormat("yyyyMMddHHmm").format(currentTime.getTime()));
				
				try{
					if(task != null){
						task.stopTask();
					}
					task = new Tasks();
					task.setCurrentTime(currentTime);
					task.start();
					
				} catch (Exception exs) {
					// TODO: handle exception
					logger.error("输入的时间不正确!");
					MessageBox.showMessageBox(READER.getProperty("message.frame.title"), "启动不正确!");
					return ;
				}
				MessageBox.showMessageBox(READER.getProperty("message.frame.title"), "设置成功!");
				FRAME.setVisible(false);
//				FRAME.dispose();
			}
			
		});
		sure.setPreferredSize(new Dimension(60, 30));
		sure.setFont(new Font("黑体",Font.BOLD,12));
		cancel.addActionListener(new ActionListener(){

			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(FRAME != null){
					FRAME.setVisible(false);
				}
			}
			
		});
		cancel.setFont(new Font("黑体",Font.BOLD,12));
		cancel.setPreferredSize(new Dimension(60, 30));
		buttonPanel.add(sure);
		buttonPanel.add(cancel);
		buttonPanel.doLayout();
		buttonPanel.updateUI();
		southPanel.add(buttonPanel);
		FRAME.addWindowListener(new DefaultWindowListener());
//		FRAME.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		FRAME.setTitle(READER.getProperty("system.picker.frame.title"));
		FRAME.setSize(320, 300);
		FRAME.setLocationRelativeTo(null);
		FRAME.setLayout(new BorderLayout());
		panel.setPreferredSize(new Dimension(300, 180));
		
		panel.addActionListener(new ActionListener(){
			
			/**
			 * (non-Javadoc)
			 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
			 */
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				Object obj = e.getSource();
				if(obj instanceof JDatePanelImpl){
					JDatePanelImpl jdp = (JDatePanelImpl)obj;
					DateModel<?> model = jdp.getModel();
					currentTime.set(model.getYear(), model.getMonth(), model.getDay());
					logger.info(new SimpleDateFormat("yyyyMMddHHmm").format(currentTime.getTime()));
					int hou = 0;
					int min = 0;
					try {
						hou = Integer.parseInt(hour.getSelectedItem().toString());
						min = Integer.parseInt(minute.getSelectedItem().toString());
						if(min > 59 || hou > 23){
							MessageBox.showMessageBox(READER.getProperty("message.frame.title"), "输入时间不正确!");
							return ;
						}
						
					} catch (NumberFormatException ex) {
						logger.error("输入的时间不正确!");
						MessageBox.showMessageBox(READER.getProperty("message.frame.title"), "输入时间不是数字格式!");
						return ;
					}
					
					currentTime.set(Calendar.HOUR_OF_DAY, hou);
					currentTime.set(Calendar.MINUTE, min);
					
					logger.info("输入时间为:" + new SimpleDateFormat("yyyyMMddHHmm").format(currentTime.getTime()));
				}
			}
			
		});
		northPanel.setPreferredSize(new Dimension(300, 180));
		northPanel.add(panel);
		this.add(northPanel,BorderLayout.NORTH);
		this.add(timePanel,BorderLayout.CENTER);
		this.add(southPanel,BorderLayout.SOUTH);
		this.setIconImage(READER.getImage(READER.getProperty("message.frame.icon")));
	}
	
	/**
	 * 打开日历时间设置窗口
	 */
	public static void open(){
		if(FRAME == null) {
			FRAME = new JDatePickerFrame();
			logger.info("开始初始化窗口...");
			currentTime = Calendar.getInstance();
			FRAME.initialize();
			FRAME.setResizable(Boolean.FALSE);
			FRAME.repaint();
			logger.info("初始化窗口完毕!");
		}
		
		FRAME.setVisible(true);
		logger.info("已经打开窗口!");
	}
	
	/**  窗口是否关闭 **/
	public static boolean visible(){
		if(FRAME != null){
			return FRAME.isVisible();
		}
		return false;
	}
	
	//值改变事件
	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel("com.birosoft.liquid.LiquidLookAndFeel");//Windows外观
			logger.error("加载外观：com.birosoft.liquid.LiquidLookAndFeel");
			LiquidLookAndFeel.setLiquidDecorations(true,"mac");
			logger.error("设置为苹果：mac");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error("不支持外观：com.birosoft.liquid.LiquidLookAndFeel");
		}
		JDatePickerFrame.open();
	}
	
//	private class TextFieldValueChanage implements DocumentListener{
//
//		public void changedUpdate(DocumentEvent e) {
//			// TODO Auto-generated method stub	
//			update();
//		}
//
//		public void insertUpdate(DocumentEvent e) {
//			// TODO Auto-generated method stub
//			update();
//		}
//
//		public void removeUpdate(DocumentEvent e) {
//			// TODO Auto-generated method stub
//			update();
//		}
//		
//		private void update(){
//			int hou = 0;
//			int min = 0;
//			try {
//				hou = Integer.parseInt(hour.getSelectedItem().toString());
//				min = Integer.parseInt(minute.getSelectedItem().toString());
//				if(hou > 23){
//					logger.info("输入小时不在[0-23]内!");
//					MessageBox.showMessageBox(READER.getProperty("message.frame.title"), "输入小时[0-23]!");
//					return ;
//				}
//				if(min > 59){
//					logger.info("输入分钟不在[0-59]内!");
//					MessageBox.showMessageBox(READER.getProperty("message.frame.title"), "输入分钟[0-59]!");
//					return ;
//				}
//				
//				
//			} catch (NumberFormatException ex) {
//				logger.error("输入的时间不是数字格式!");
//				MessageBox.showMessageBox(READER.getProperty("message.frame.title"), "输入时间不是数字格式!");
//				return ;
//			}
//			
//			currentTime.set(Calendar.HOUR_OF_DAY, hou);
//			currentTime.set(Calendar.MINUTE, min);
//			logger.info("输入时间为:" + new SimpleDateFormat("yyyyMMddHHmm").format(currentTime.getTime()));
//		}
//		
//	}
}
